package org.jeecg.modules.demo.ch.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.ch.Utils.DateUtil;
import org.jeecg.modules.demo.ch.common.CommonMst;
import org.jeecg.modules.demo.ch.entity.ChDailyRecord;
import org.jeecg.modules.demo.ch.entity.ChDailyRecordDetails;
import org.jeecg.modules.demo.ch.service.IChDailyRecordDetailsService;
import org.jeecg.modules.demo.ch.service.IChDailyRecordService;
import org.jeecg.modules.demo.ch.vo.ChDailyRecordPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 每日记录
 * @Author: jeecg-boot
 * @Date:   2022-11-29
 * @Version: V1.0
 */
@Api(tags="每日记录")
@RestController
@RequestMapping("/ch/chDailyRecord")
@Slf4j
public class ChDailyRecordController {
	@Autowired
	private IChDailyRecordService chDailyRecordService;
	@Autowired
	private IChDailyRecordDetailsService chDailyRecordDetailsService;

	/**
	 * 分页列表查询
	 *
	 * @param chDailyRecord
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "每日记录-分页列表查询")
	@ApiOperation(value="每日记录-分页列表查询", notes="每日记录-分页列表查询")
//	@GetMapping(value = "/list")
	// 需要将前端将list请求地址改成此地址
	@GetMapping(value = "/mpList")
	@PermissionData(pageComponent = "weekReport/ChDailyRecordList")
	public Result<IPage<ChDailyRecord>> queryPageList(ChDailyRecord chDailyRecord,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {

//		QueryWrapper<ChDailyRecord> queryWrapper = QueryGenerator.initQueryWrapper(chDailyRecord, req.getParameterMap());
		String title = chDailyRecord.getTitle();//标题
		String name = chDailyRecord.getName();//姓名
		String data_begin = StringUtils.hasLength(chDailyRecord.getData_begin()) ? chDailyRecord.getData_begin().toString() : null;//查询开始日期
		String data_end = StringUtils.hasLength(chDailyRecord.getData_end()) ? chDailyRecord.getData_end().toString() : null;//查询结束日期

		if (data_begin != null) {
			data_begin = data_begin.substring(1, 11);
		}
		if (data_end != null) {
			data_end = data_end.substring(1, 11);
		}

		//结束日期+1天
		if (StringUtils.hasLength(data_end)) {
			LocalDate date = LocalDate.parse(data_end);
			LocalDate localDate = date.plusDays(1);
			DateTimeFormatter df = DateTimeFormatter.ofPattern(CommonMst.WEEKLYREPORT.DATEFORMAT);
			data_end = localDate.format(df);
		}

		//加载数据权限
		//此处使用的是QueryWrapper，如果你需要用LambdaQueryWrapper，请先new一个QueryWrapper，接着加载数据权限，然后通过queryWrapper.lambda()将其转化成LambdaQueryWrapper，最后你就能使用LambdaQueryWrapper处理自己的逻辑了
		QueryWrapper<ChDailyRecord> queryWrapper = new QueryWrapper<>();
		//调用这个QueryGenerator.installAuthMplus方法加载数据权限
		QueryGenerator.installAuthMplus(queryWrapper, ChDailyRecord.class);
		//开始处理自己的逻辑
		LambdaQueryWrapper<ChDailyRecord> chDailyRecordLambdaQueryWrapper = queryWrapper.lambda()
				.like(StringUtils.hasLength(title), ChDailyRecord::getTitle, title)
				.like(StringUtils.hasLength(name), ChDailyRecord::getName, name)
				.ge(data_begin != null, ChDailyRecord::getData, data_begin)
				.le(data_end != null, ChDailyRecord::getData, data_end)
				.orderByDesc(ChDailyRecord::getName)
				.orderByDesc(ChDailyRecord::getCreateTime);
		Page<ChDailyRecord> page = new Page<ChDailyRecord>(pageNo, pageSize);
		IPage<ChDailyRecord> pageList = chDailyRecordService.page(page, chDailyRecordLambdaQueryWrapper);
		return Result.OK(pageList);
	}

	 /**
	  * 生成本周计划表标题
	  *
	  * @return
	  */
	 public static String generateWeeklyTitle() {
		 //获取本周一的日期
		 SimpleDateFormat sf=new SimpleDateFormat(CommonMst.WEEKLYREPORT.DATEFORMAT);
		 String nextMonday = sf.format(DateUtil.getThisWeek().get("monday"));//本周一
		 LocalDate localDate = LocalDate.parse(nextMonday, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		 String date = localDate.toString();
		 int weekByWed = 0;//获取第几周
		 try {
			 weekByWed = DateUtil.getWeekByWed(date, CommonMst.WEEKLYREPORT.DATEFORMAT);
		 } catch (Exception e) {
			 log.error("每日记录-生成本周计划表标题异常", e);
			 e.printStackTrace();
		 }
		 //由于日期固定 所以不用减1月
//		 if (weekByWed > 4){
//			 //大于4 月份减一
//			 localDate = localDate.minusMonths(1);
//		 }
		 int  year = localDate.getYear();//获取年
		 int month = localDate.getMonthValue();//获取月

		 StringBuilder sb = new StringBuilder();
		 String title = sb.append(year).append("年").append(month).append("月第").append(weekByWed).append("周").toString();
		 log.info("当前本周一的日期:{},属于当月的第{}周,生成的标题title:{}", date, weekByWed, title);
		 return title;
	 }


	/**
	 *   添加
	 *
	 * @param chDailyRecordPage
	 * @return
	 */
	@AutoLog(value = "每日记录-添加")
	@ApiOperation(value="每日记录-添加", notes="每日记录-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ChDailyRecordPage chDailyRecordPage) {
		ChDailyRecord chDailyRecord = new ChDailyRecord();
		BeanUtils.copyProperties(chDailyRecordPage, chDailyRecord);
		chDailyRecord.setTitle(generateWeeklyTitle());//设置标题
		chDailyRecordService.saveMain(chDailyRecord, chDailyRecordPage.getChDailyRecordDetailsList());
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param chDailyRecordPage
	 * @return
	 */
	@AutoLog(value = "每日记录-编辑")
	@ApiOperation(value="每日记录-编辑", notes="每日记录-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ChDailyRecordPage chDailyRecordPage) {
		ChDailyRecord chDailyRecord = new ChDailyRecord();
		BeanUtils.copyProperties(chDailyRecordPage, chDailyRecord);
		ChDailyRecord chDailyRecordEntity = chDailyRecordService.getById(chDailyRecord.getId());
		if(chDailyRecordEntity==null) {
			return Result.error("未找到对应数据");
		}
		chDailyRecordService.updateMain(chDailyRecord, chDailyRecordPage.getChDailyRecordDetailsList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "每日记录-通过id删除")
	@ApiOperation(value="每日记录-通过id删除", notes="每日记录-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		chDailyRecordService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "每日记录-批量删除")
	@ApiOperation(value="每日记录-批量删除", notes="每日记录-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.chDailyRecordService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "每日记录-通过id查询")
	@ApiOperation(value="每日记录-通过id查询", notes="每日记录-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ChDailyRecord> queryById(@RequestParam(name="id",required=true) String id) {
		ChDailyRecord chDailyRecord = chDailyRecordService.getById(id);
		if(chDailyRecord==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(chDailyRecord);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "每日记录明细表通过主表ID查询")
	@ApiOperation(value="每日记录明细表主表ID查询", notes="每日记录明细表-通主表ID查询")
	@GetMapping(value = "/queryChDailyRecordDetailsByMainId")
	public Result<List<ChDailyRecordDetails>> queryChDailyRecordDetailsListByMainId(@RequestParam(name="id",required=true) String id) {
		List<ChDailyRecordDetails> chDailyRecordDetailsList = chDailyRecordDetailsService.selectByMainId(id);
		return Result.OK(chDailyRecordDetailsList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param chDailyRecord
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ChDailyRecord chDailyRecord) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<ChDailyRecord> queryWrapper = QueryGenerator.initQueryWrapper(chDailyRecord, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
          List<String> selectionList = Arrays.asList(selections.split(","));
          queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<ChDailyRecord> chDailyRecordList = chDailyRecordService.list(queryWrapper);

      // Step.3 组装pageList
      List<ChDailyRecordPage> pageList = new ArrayList<ChDailyRecordPage>();
      for (ChDailyRecord main : chDailyRecordList) {
          ChDailyRecordPage vo = new ChDailyRecordPage();
          BeanUtils.copyProperties(main, vo);
          List<ChDailyRecordDetails> chDailyRecordDetailsList = chDailyRecordDetailsService.selectByMainId(main.getId());
          vo.setChDailyRecordDetailsList(chDailyRecordDetailsList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "每日记录列表");
      mv.addObject(NormalExcelConstants.CLASS, ChDailyRecordPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("每日记录数据", "导出人:"+sysUser.getRealname(), "每日记录"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ChDailyRecordPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ChDailyRecordPage.class, params);
              for (ChDailyRecordPage page : list) {
                  ChDailyRecord po = new ChDailyRecord();
                  BeanUtils.copyProperties(page, po);
                  chDailyRecordService.saveMain(po, page.getChDailyRecordDetailsList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
